Majority Element

Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.

题目大意:找出数组中出现次数超过一半的数

题目难度:Easy

/**
 * Created by gzdaijie on 16/6/19
 */
public class Solution {
    public int majorityElement(int[] nums) {
        int cnt = 1;
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == result) cnt++;
            else {
                cnt--;
                if (cnt == 0) {
                    result = nums[i];
                    cnt = 1;
                }
            }
        }
        return result;
    }
}
gzdaijie            updated 2016-06-19 23:37:21

results matching ""

    No results matching ""